﻿using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.Order;
using ZBJF.Warranty.Model.ViewModel.Product;

namespace ZBJF.Warranty.BLL
{
    public partial class InsuranceOrderService
    {
        public InsuranceOrder LoadByID(long id)
        {
            return LoadEntities(a => a.ID == id).FirstOrDefault();
        }

        //public bool IsExist(string thirdOrderNo, ref InsuranceOrder entity)
        //{
        //    entity = LoadByThirdOrderNo(thirdOrderNo.Trim());
        //    return entity != null;
        //}

        public bool IsExistByThirdUniqueNumber(string thirdUniqueNumber, ref InsuranceOrder entity)
        {
            entity = LoadByThirdUniqueNumber(thirdUniqueNumber.Trim());
            return entity != null;
        }

        public InsuranceOrder LoadByIMEIOrIDFV(string searchNo)
        {
            return LoadEntities(c => c.IMEI == searchNo || c.IDFV == searchNo).FirstOrDefault();
        }

        //public InsuranceOrder LoadByThirdOrderNo(string thirdOrderNo)
        //{
        //    return LoadEntities(c => c.ThirdOrderNO.Equals(thirdOrderNo)).FirstOrDefault();
        //}

        public InsuranceOrder LoadByThirdUniqueNumber(string thirdUniqueNumber)
        {
            return LoadEntities(c => c.ThirdUniqueNumber == thirdUniqueNumber).FirstOrDefault();
        }

        #region 根据获取工单信息 + InsuranceOrder LoadBySellerBusinessNo(string sellerBusinessNo, long ID)
        /// <summary>
        /// 根据获取工单信息
        /// </summary>
        /// <param name="sellerBusinessNo">销售商订单号</param>
        /// <param name="ID">销售商ID</param>
        /// <returns></returns>
        public InsuranceOrder LoadBySellerBusinessNo(string sellerBusinessNo, long ID)
        {
            return LoadEntities(c => c.SellerBusinessNo == sellerBusinessNo).FirstOrDefault();
        } 
        #endregion

        #region 根据获取工单信息 + InsuranceOrder LoadByThirdUniqueNumber(string thirdUniqueNumber, long ID)
        /// <summary>
        /// 根据获取工单信息
        /// </summary>
        /// <param name="thirdUniqueNumber">第三方保单号</param>
        /// <param name="ID">销售商ID</param>
        /// <returns></returns>
        public InsuranceOrder LoadByThirdUniqueNumber(string thirdUniqueNumber, long ID)
        {
            return LoadEntities(t => t.ThirdUniqueNumber == thirdUniqueNumber && t.SaleVendorId == ID).FirstOrDefault();
        }
        #endregion

        #region 根据获取工单信息 + InsuranceOrder LoadByIMEI(long ID, string IMEI)
        /// <summary>
        /// 根据获取工单信息
        /// </summary>
        /// <param name="ID">销售商ID</param>
        /// <param name="IMEI">设备识别码IMEI</param>
        /// <returns></returns>
        public List<InsuranceOrder> LoadByIMEI(long ID, string IMEI)
        {
            return  LoadEntities(t => t.IMEI == IMEI && t.SaleVendorId == ID).ToList();
        }
        #endregion
        public InsuranceOrder LoadByPhoneAndCertificateNO(string orderPhone, string certificateNO)
        {
            return LoadEntities(c => c.UserPhone == orderPhone && c.CertificateNO == certificateNO).FirstOrDefault();
        }

        public bool ValidateCreateAccident(string orderPhone, string certificateNO, out long orderId, ref string msg)
        {
            orderId = 0;
            var order = LoadByPhoneAndCertificateNO(orderPhone, certificateNO);
            //1. 判断订单是否生效
            //2. 判断订单是否在有效期内
            //3.判断是否理赔过
            if (order != null)
            {
                if (order.Effective.HasValue && order.Effective.Value && order.OrderStatus == (byte)InsuranceOrderStatus.HadEffective)
                {
                    if (order.ServiceStartTime.HasValue &&
                        order.ServiceEndTime.HasValue &&
                        DateTime.Now >= order.ServiceStartTime.Value &&
                        DateTime.Now <= order.ServiceEndTime.Value)
                    {
                        if (!order.InsuranceWarrantyRecord.Any())
                        {
                            return true;
                        }
                        else
                        {
                            msg = "该保单已理赔过.";
                            return false;
                        }
                    }
                    else
                    {
                        msg = "理赔时间不合法或已过保期.";
                        return false;
                    }
                }
                else
                {
                    msg = "该保单未生效.";
                    return false;
                }
            }
            else
            {
                msg = "该保单不存在";
                return false;
            }
        }

        public InsuranceOrder Load(string cardNo, string cardPassword)
        {
            return LoadEntities(c => c.CardNo == cardNo && c.CardPwd == cardPassword).FirstOrDefault();
        }

        public IQueryable<InsuranceOrder> GetPagingList(InsuranceOrderModel model, out int total)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceOrder>();
            if (model.OrderFromType > 0)
            {
                expressionWhere = expressionWhere.And(o => o.OrderFromType == model.OrderFromType);
            }
            if (model.ProductTypeId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.ProductTypeId == model.ProductTypeId);
            }
            if (model.OrderStatus.HasValue)
            {
                expressionWhere = expressionWhere.And(o => o.OrderStatus == model.OrderStatus.Value);
            }
            if (model.CreateOrderTimeStart.HasValue)
            {
                expressionWhere = expressionWhere.And(o => o.CreateOrderTime >= model.CreateOrderTimeStart.Value);
            }
            if (model.CreateOrderTimeEnd.HasValue)
            {
                expressionWhere = expressionWhere.And(o => o.CreateOrderTime < SqlFunctions.DateAdd("dd", 1, model.CreateOrderTimeEnd.Value));
            }
            if (!string.IsNullOrWhiteSpace(model.OrderNO))
            {
                expressionWhere = expressionWhere.And(o => o.OrderNO.Contains(model.OrderNO.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.UserPhone))
            {
                expressionWhere = expressionWhere.And(o => o.UserPhone.Contains(model.UserPhone.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.UserName))
            {
                expressionWhere = expressionWhere.And(o => o.UserName.Contains(model.UserName.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.CertificateNO))
            {
                expressionWhere = expressionWhere.And(o => o.CertificateNO.Contains(model.CertificateNO.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.InsuranceCategoryName))
            {
                expressionWhere = expressionWhere.And(o => o.InsuranceCategoryName.Contains(model.InsuranceCategoryName.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.IMEI))
            {
                expressionWhere = expressionWhere.And(o => o.IMEI.Equals(model.IMEI.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.CardNo))
            {
                expressionWhere = expressionWhere.And(o => o.CardNo.Contains(model.CardNo.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.ThirdOrderNO))
            {
                expressionWhere = expressionWhere.And(o => o.ThirdOrderNO.Contains(model.ThirdOrderNO.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.InsuranceCompany))
            {
                expressionWhere = expressionWhere.And(o => o.InsuranceCompany.Contains(model.InsuranceCompany.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.InsuranceCompanyBranch))
            {
                expressionWhere = expressionWhere.And(o => o.InsuranceCompanyBranch.Contains(model.InsuranceCompanyBranch.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.SaleVendorName))
            {
                expressionWhere = expressionWhere.And(o => o.SaleVendorName.Contains(model.SaleVendorName.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(model.Keyword))
            {
                expressionWhere = expressionWhere.And(o => (o.CardNo + SqlFunctions.Space(1) + o.OrderNO + SqlFunctions.Space(1) + o.CertificateNO + SqlFunctions.Space(1) + o.IMEI + SqlFunctions.Space(1) + o.UserPhone + SqlFunctions.Space(1) + o.UserName).Contains(model.Keyword.Trim()));
            }
            if (model.CanCreatedWarranty.HasValue)
            {
                var currentTime = DateTime.Now;
                expressionWhere =
                    expressionWhere.And(
                        c =>
                            c.Effective == true && c.ServiceStartTime <= currentTime && c.ServiceEndTime >= currentTime &&
                            (!c.InsuranceWarrantyRecord.Any() ||
                             c.InsuranceWarrantyRecord.All(x => x.Status == (int)InsuranceWarrantyStatus.Canceled || x.Status == (int)InsuranceWarrantyStatus.Refuse))); //取消报案、拒保的可以继续报案
            }
            if (model.ServiceStartTime.HasValue)
            {
                expressionWhere =
                    expressionWhere.And(o => o.ServiceStartTime >= model.ServiceStartTime);
            }
            if (model.ServiceEndTime.HasValue)
            {
                expressionWhere =
                    expressionWhere.And(o => o.ServiceEndTime < SqlFunctions.DateAdd("dd", 1, model.ServiceEndTime));
            }
            if (!string.IsNullOrWhiteSpace(model.OrderStatusString))
            {
                var statusList = model.OrderStatusString.Split(',').ToList().ConvertAll(byte.Parse);
                expressionWhere = expressionWhere.And(o => statusList.Contains(o.OrderStatus));
            }
            if (!string.IsNullOrWhiteSpace(model.ExcludeOrderStatusString))
            {
                var statusList = model.ExcludeOrderStatusString.Split(',').ToList().ConvertAll(byte.Parse);
                expressionWhere = expressionWhere.And(o => !statusList.Contains(o.OrderStatus));
            }
            return LoadPagerEntities<InsuranceOrder>(model.PageIndex, model.iDisplayLength, out total, expressionWhere, model.iSorts);
        }

        #region 审核保单——尺度销售商
        /// <summary>
        /// 审核保单——尺度销售商
        /// </summary>
        /// <param name="">保单号</param>
        /// <param name="">是否通过</param>
        /// <param name="">最后修改时间——并发控制</param>
        /// <param name="">最后审核人账号</param>
        /// <param name="">最后审核人姓名</param>
        /// <returns></returns>
        public bool UpdateInsuranceOrderStatus(long insuranceOrderId, bool isPass, DateTime lastModifyTime, string opUserName)
        {
            byte status = isPass ? (byte)InsuranceOrderStatus.ApprovedAndPassed : (byte)InsuranceOrderStatus.ApprovedButNotPassed;
            string sql =string.Format("UPDATE InsuranceOrder SET OrderStatus={0},LastCheckUser={1},LastCheckTime={2} WHERE insuranceOrderId={3} AND lastModifyTime={4}", status, opUserName,DateTime.Now, insuranceOrderId, lastModifyTime);
           return ExcuteSql(sql, new System.Data.SqlClient.SqlParameter[] { new System.Data.SqlClient.SqlParameter() })>0;
        }
        #endregion

    }
}
